package sm.hibernate.type;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;

import sm.codec.type.Logical;
import sm.codec.type.NullValue;

public class LogicalType extends AbstractPrimitiveType {

	@Override
	public int[] sqlTypes() {
		return new int[] { Types.CHAR };
	}

	@Override
	public Class returnedClass() {
		return Logical.class;
	}

	@Override
	public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {
		Character value = (Character) Hibernate.CHARACTER.nullSafeGet(rs,
				names, null, owner);
		if (value != null) {
			if (value.equals('t') || value.equals('T')) {
				return Logical.TRUE;
			} else if (value.equals('f') || value.equals('F')) {
				return Logical.FALSE;
			} else if (value.equals('u') || value.equals('U')) {
				return Logical.UNKNOWN;
			} else {
				return NullValue.LogicalNull;
			}
		} else {
			return NullValue.LogicalNull;
		}
	}

	@Override
	public void nullSafeSet(PreparedStatement st, Object value, int index)
			throws HibernateException, SQLException {
		Character charValue = null;
		if (value instanceof Logical) {
			Logical logical = (Logical) value;
			if (logical == Logical.TRUE) {
				charValue = 't';
			} else if (logical == Logical.FALSE) {
				charValue = 'f';
			} else if (logical == Logical.UNKNOWN) {
				charValue = 'u';
			}
		}
		Hibernate.CHARACTER.nullSafeSet(st, charValue, index);
	}

}
